package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.mapper.PartnerMapper;
import com.heima.pojo.Partner;
import com.heima.pojo.dto.PartnerDto;
import com.heima.pojo.vo.PartnerVo;
import com.heima.service.PartnerService;
import com.heima.utils.PageResult;
import lombok.RequiredArgsConstructor;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 赵超
 */
@Service
@RequiredArgsConstructor
public class PartnerServiceImpl extends ServiceImpl<PartnerMapper, Partner> implements PartnerService {

    private final PartnerMapper partnerMapper;

    @Override
    public PageResult<PartnerVo> page(Integer pageIndex, Integer pageSize, String name) {
        PageHelper.startPage(pageIndex, pageSize);
        Page<PartnerVo> list = partnerMapper.page(name);
        return new PageResult<>(list.getPageNum(), list.getPageSize(), list.getPages(), list.getTotal(), list);
    }

    @Override
    public Integer add(PartnerDto partnerDto) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDto, partner);
        String rawPassword = partner.getPassword();
        String hashed = BCrypt.hashpw(rawPassword, BCrypt.gensalt(12));
        partner.setPassword(hashed);
        partner.setCreateTime(LocalDateTime.now());
        partner.setUpdateTime(LocalDateTime.now());

        return partnerMapper.insert(partner);
    }

    @Override
    public PartnerVo getPartnerById(Integer id) {
        return partnerMapper.getPartnerById(id);
    }

    @Override
    public Integer updatePartnerById(Integer id, PartnerDto partnerDto) {
        return partnerMapper.updatePartnerById(id, partnerDto);
    }

    @Override
    public Integer deleteById(Integer id) {
        return partnerMapper.deleteById(id);
    }
}
